<?php
$host = "192.168.1.100";
$host = "114.113.155.174";
$port = 8000;

$key = "serverkey";
$uid = uniqid("php");
$nickname = $uid;

$host = "s4.mysticalcard.com";
chat_stat(2);

/**
$host = "s1.mysticalcard.com";
chat_stat();
$host = "s2.mysticalcard.com";
chat_stat();
$host = "s3.mysticalcard.com";
chat_stat();
$host = "s4.mysticalcard.com";
chat_stat();
$host = "s5.mysticalcard.com";
chat_stat();
//**/

function chat_stat($sub_type=1)
{
	global $host, $port, $key, $nickname,$uid;

	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	$result = socket_connect($socket, $host, $port);
	
	// 设置接收缓冲区为10M
	socket_set_option ( $socket, SOL_SOCKET, SO_RCVBUF, 1024 * 1024 * 10 );

	$login_pack = s(100) . str($key) .str($uid) . str($nickname);

	//$sub_type = 2;
	$stat_pack = s(114) . i($sub_type);

	write_pack($socket, $login_pack , $stat_pack);

	$pack_len = 0;
	while($result = wait_pack($socket)){
		$pack_len++;

		if ($result['type'] == 115){
			echo $host . ':' . $result['ret']['str'] . "\r\n";
			break;
		}
	}
}

function write_pack($socket, $str)
{
	$num=func_num_args(); 
	$list=func_get_args(); 

	$wstr = "";
	for($i = 1; $i < $num; $i++)
	{
		$pack_len = strlen($list[$i]);
		$wstr .= i($pack_len) . $list[$i];
	}
	if (@socket_write($socket, $wstr) === false){
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		exit("fwrite fail! code:$errorcode error:$errormsg\n");
	}
}
function wait_pack($socket)
{
	$data = @socket_read ($socket, 4);
	if (strlen($data) == 0){
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		exit("socket_read  is 0 closed code:$errorcode, error:$errormsg\n");
	}

	$len = current(unpack("i", $data));
	$type = current(unpack("s", socket_read ($socket, 2)));
	
	if ($len > 2 && $type != 115)
		$data = socket_read ($socket, $len - 2);
	
	$ret = array();

	if ($type == 101){
		$ret['status'] = current(unpack("i", $data));
	}elseif($type == 5){
		$ret['errortype'] = current(unpack("i", $data));
	}elseif($type == 115){
		$ret['sub_type'] = current(unpack("i", socket_read ($socket, 4)));
		$str_len = current(unpack("i", socket_read ($socket, 4)));

		$data = "";
		$r_len = 0;
		do { 
			$recv = ""; 
			$recv = socket_read($socket, $str_len); 
			if($recv != "")
				$data .= $recv;
			$r_len += strlen($recv);
		} while($recv != false && $r_len < $str_len);
		
		$ret['str'] = $data;//current(unpack("c*", $data));
	}

	return array("len" => $len, "type" => $type,'ret' => $ret);
}

// 封装字符串
function str($str)
{
	if ($str == NULL)
		return "";
	else
		return pack("i",strlen($str)) .   $str;
}

// 封装int
function i($i)
{
	return pack("i", $i);
}

// 封装short
function s($s)
{
	return pack("s", $s);
}
